package meblog.online.server.controller;

import lombok.extern.slf4j.Slf4j;
import meblog.online.server.config.SystemException;
import meblog.online.server.utils.ResultCode;
import meblog.online.server.utils.ResultMessage;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * @author: Eternity.麒麟
 * @description: 异常处理
 * @date: 2022/10/17 10:53
 * @version: 1.0
 */
@Slf4j
@RestControllerAdvice
public class ExceptionController {


    @ResponseBody
    @ExceptionHandler(value = SystemException.class)
    public ResultMessage<String> systemExceptionHandler(HttpServletRequest request, SystemException exception) {
        log.error("发生业务异常: {}", exception.getMsg());
        return new ResultMessage<>(exception.getCode(), exception.getMsg(), exception.getMessage());
    }

    /**
     * 处理空指针的异常
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultMessage<String> exceptionHandler(HttpServletRequest request, NullPointerException exception){
        log.error("发生空指针异常原因是: {}", exception.getMessage());
        return new ResultMessage<>(ResultCode.FAIL, exception.getMessage());
    }


    /**
     * 处理其他异常
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultMessage<String> exceptionHandler(HttpServletRequest request, Exception exception){
        log.error("未定制的异常: {}", exception.getMessage());
        if (exception instanceof DataAccessException) {
            return new ResultMessage<>(ResultCode.FAIL, "数据处理异常");
        } else {
            return new ResultMessage<>(ResultCode.FAIL, exception.getMessage());
        }
    }


}
